import express from "express";
import path from "path";
import fs from "node:fs/promises";
import { marked } from "marked";
import hljs from "highlight.js";
// 导入 JavaScript 语言定义
import javascript from "highlight.js/lib/languages/javascript";

let router = express.Router();

// 注册 JavaScript 语言
hljs.registerLanguage("javascript", javascript);

// 配置 marked
marked.setOptions({
  gfm: true,
  breaks: true,
});

// 创建自定义渲染器
const renderer = new marked.Renderer();

renderer.code = function (code, language) {
  // 获取代码内容和语言
  const codeStr = typeof code === "object" ? code.text : code;
  const lang = language || (typeof code === "object" ? code.lang : null);

  try {
    if (lang === "javascript" || lang === "js") {
      // 使用更详细的配置
      const result = hljs.highlight(codeStr, {
        language: "javascript",
        ignoreIllegals: true,
      });

      // 对结果进行后处理，增强参数高亮
      let html = result.value
        // 匹配函数参数
        .replace(/\((.*?)\)/g, (match, params) => {
          if (!params) return "()";
          // 将参数分割并添加高亮类
          const highlightedParams = params
            .split(",")
            .map((param) => `<span class="hljs-params">${param.trim()}</span>`)
            .join(",");
          return `(${highlightedParams})`;
        });

      return `<pre><code class="hljs language-javascript">${html}</code></pre>`;
    }

    if (lang && hljs.getLanguage(lang)) {
      const result = hljs.highlight(codeStr, { language: lang });
      return `<pre><code class="hljs language-${lang}">${result.value}</code></pre>`;
    }

    // 如果没有指定语言，使用 plaintext
    const result = hljs.highlight(codeStr, { language: "plaintext" });
    return `<pre><code class="hljs">${result.value}</code></pre>`;
  } catch (err) {
    console.error("Highlight error:", err);
    return `<pre><code class="hljs">${codeStr}</code></pre>`;
  }
};

// 设置渲染器
marked.setOptions({ renderer });

export default function (basedir) {
  router.get("/*", (req, res, next) => {
    let url = req.params[0];
    // if (url === "") url = "index.md";
    if (url === "") url = "index.md";
    let p = path.join(basedir, `${url}`);
    console.log({ basedir, url, p });

    console.log(`[${new Date().toISOString()}] Accessing: ${url}`);

    fs.readFile(p)
      .then((buf) => {
        const content = marked.parse(buf.toString());
        res.render("markdown", {
          content,
          title: url.replace(".md", ""),
        });
        console.log(`[${new Date().toISOString()}] Success: ${url}`);
      })
      .catch((err) => {
        console.error(
          `[${new Date().toISOString()}] Error: ${url}`,
          err.message
        );
        next();
      });
  });

  return router;
}
